/************************************************************************/
/* 
*/
/************************************************************************/

#include "mainwindow.h"
#include <iostream>
#include <cstring>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iconv.h>

static MainWindow *thisObject;

MainWindow::MainWindow(EGLNativeDisplayType nativeDpy, EGLNativeWindowType nativeWindow)
: m_nativeDpy(nativeDpy)
, m_nativeWindow(nativeWindow)
{
	thisObject = this;
	EGLint major, minor;
	egldpy = eglGetDisplay(nativeDpy);
	eglInitialize(egldpy, &major, &minor);
}

MainWindow::~MainWindow(void)
{
	eglMakeCurrent( egldpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
	eglTerminate( egldpy );
	eglReleaseThread();
}

string MainWindow::applicationPath()
{
	char modulepath[1024];
	ssize_t len;
	if ( (len = readlink("/proc/self/exe", modulepath, sizeof(modulepath)-1)) != -1 ) {
		modulepath[len] = '\0';		
	}

	std::string s1(modulepath);
	int pos = s1.rfind('/');
	if( pos != s1.npos ) {
		std::string s2( modulepath, pos);
		return s2;
	}

	return std::string();
}


void MainWindow::loadResource( std::string & r, std::string _path  )
{
	const char* fp = _path.c_str();
	FILE * pFile;
	long lSize;
	char * buffer;
	size_t result;

	pFile = fopen ( fp , "rb" );
	if (pFile==NULL) 
	{
		fputs ("File error",stderr); 
		exit (1);
	}

	// obtain file size:
	fseek (pFile , 0 , SEEK_END);
	lSize = ftell (pFile);
	rewind (pFile);

	// allocate memory to contain the whole file:
	buffer = (char*) malloc ( sizeof(char)*lSize + 1 );
	if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

	// copy the file into the buffer:
	result = fread (buffer,1,lSize,pFile);
	if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

	/* the whole file is now loaded in the memory buffer. */
	buffer[lSize] = '\0';
	r = buffer;

	// terminate
	fclose (pFile);
	free (buffer);
}

extern void getScreenSize( int& sw, int& sh );

void MainWindow::size( int& sw, int& sh )
{
	getScreenSize( sw, sh );
}

MainWindow& MainWindow::instance()
{
	if (thisObject==NULL)
	{
		printf("Error: thisObject==NULL!\n");
		exit(0);
	}

	return *thisObject;
}

EGLDisplay MainWindow::display()
{
	return egldpy;
}

EGLNativeWindowType MainWindow::nativeWindow()
{
	return m_nativeWindow;
}

std::string MainWindow::toUtf8( std::string inStr )
{
	std::string strUtf8;
	
	char *__inbuf = (char*)inStr.c_str();
	size_t __inbytesleft = inStr.length();

	char tmpBuf[1024];
	size_t bufLen = sizeof(tmpBuf);

	iconv_t cd = iconv_open("UTF-8", "GBK");
	while( __inbytesleft>0 )
	{
		char *__outbuf = tmpBuf;
		size_t __outbytesleft = bufLen;
		iconv(cd, &__inbuf, &__inbytesleft, &__outbuf, &__outbytesleft);
		strUtf8+=std::string(tmpBuf, bufLen-__outbytesleft);
	}
	iconv_close(cd);

	return strUtf8;
}

